﻿@page "/AddArticle"
@using LuckyFish.Blog.Models
@using Microsoft.EntityFrameworkCore
@inject IDbContextFactory<BlogContext> DbFactory
@inject NavigationManager navigation
@inject MessageService MessageService

<PageTitle>添加文章</PageTitle>

<ValidateForm OnValidSubmit="@Done" Model="@Model" AutoGenerateAllItem="false">
    <Row ItemsPerRow="ItemsPerRow.One">
        <BootstrapInput DisplayText="标题" @bind-Value="@Model.Title"/>
        <BootstrapInput DisplayText="简介" @bind-Value="@Model.Brief"/>
        <BootstrapInput DisplayText="文章链接" @bind-Value="@Model.UrlName"/>
        <BootstrapInput DisplayText="标题图片地址" @bind-Value="@Model.ImageUrl"/>
        <p>文章合集</p>
        <AutoComplete Items="@ArticleItems" OnSelectedItemChanged="ListSearch" Debounce="500"/>
        <PopConfirmButton Placement="Placement.Top"
                          Color="Color.Info"
                          ConfirmButtonColor="Color.Danger"
                          Text="@ListName"
                          IsAsync="true"
                          OnConfirm="@(() => { ListName = "";StateHasChanged();return Task.CompletedTask;})"
                          Content="确定要删除数据吗？"/>
        <p>文章标签</p>
        <AutoComplete Items="@LabelItems" OnSelectedItemChanged="LabelSearch" Debounce="500"/>
        <div class="row g-3">
            @foreach (var a in Labels)
            {
                <div class="col-6 col-sm-4 col-md-3 col-lg-auto">
                    <PopConfirmButton Placement="Placement.Top"
                                      IsAsync="true"
                                      OnConfirm="@(async () => await Remove(a))"
                                      Content="确定要删除数据吗？">
                        <Badge Color="Color.Primary">@a</Badge>
                    </PopConfirmButton>

                </div>
            }
        </div>
        <div style="width: 100%; height: 300px;">
            <Markdown @bind-Html="@Model.HtmlContext"/>
        </div>
    </Row>
    <Button ButtonType="ButtonType.Submit" IsAsync="true" Icon="fa-solid fa-floppy-disk">
        提交文章
    </Button>
</ValidateForm>


@code {

    protected override async Task OnInitializedAsync()
    {
        await base.OnInitializedAsync();
        var context = await DbFactory.CreateDbContextAsync();
        ArticleItems = await context.ArticleLists.Select(x => x.ListName).ToListAsync();
        LabelItems = await context.LabelLists.Select(x => x.LabelName).ToListAsync();
        await context.DisposeAsync();
    }

    private ArticleModel Model { get; set; } = new();

    private async Task Done(EditContext arg)
    {
        if (Model.IsNull())
        {
            await MessageService.Show(new MessageOption() { Content = "添加失败" });
            return;
        }
        Model.DateString = DateTime.Today.ToString("d");
        var context = await DbFactory.CreateDbContextAsync();
        if (!string.IsNullOrEmpty(ListName))
        {
            var thisList = await context.ArticleLists.FirstOrDefaultAsync(x => x.ListName == ListName);
            Model.ListId = ListName;
            Model.List = thisList ?? new ArticleList() { ListName = ListName };
        }

        ToLabel().ForEach(Action);

        context.Articles.Add(Model);
        await context.SaveChangesAsync();
        await context.DisposeAsync();
        await MessageService.Show(new MessageOption() { Content = "添加成功，正在导航至地址" });
        navigation.NavigateTo($"/Article/{Model.UrlName}", true);
        return;

        async void Action(LabelList x)
        {
            var inquire = await context.LabelLists.FirstOrDefaultAsync(list => list.LabelName == x.LabelName.Replace(" ", ""));
            if (inquire == null)
            {
                context.LabelLists.Add(x);
                await context.SaveChangesAsync();
                Model.Labels.Add(x);
            }
            else
            {
                Model.Labels.Add(inquire);
            }
        }
    }

    public IEnumerable<string>? ArticleItems { get; set; }
    private string? ListName { get; set; }

    public IEnumerable<string>? LabelItems { get; set; }
    private List<string> Labels { get; set; } = new();

    private List<LabelList> ToLabel()
        => Labels.Select(label => new LabelList() { LabelName = label }).ToList();

    private Task ListSearch(string arg)
    {
        ListName = arg;
        StateHasChanged();
        return Task.CompletedTask;
    }

    private Task LabelSearch(string arg)
    {
        if (Labels.All(x => x != arg))
            Labels.Add(arg);
        StateHasChanged();
        return Task.CompletedTask;
    }

    private Task Remove(string arg)
    {
        if (Labels.All(x => x != arg))
            Labels.Remove(arg);
        StateHasChanged();
        return Task.CompletedTask;
    }

}